var home = 'http://localhost:2907/';
var longUrl;
var port;

chrome.self.onConnect.addListener(chrome_connect);

function chrome_connect(p) {
	port = p;
    port.onMessage.addListener(msg_recv);
}

function msg_recv(data) {
	if (data.command == 'url_change') {
		url_change(data.url);
	} else if (data.command == 'save_form') {
		post_form(data);
	}
}

function url_change(longUrl) {
	if (longUrl) {
		load_logins(longUrl);
	}
}

function debug(data) {
	$('#debug').html(data);
}

function load_logins(longUrl) {
	 debug('login list...');
	 $.get( home + "?type=load&url=" + longUrl, {}, get_logins);
	 $('#logins').html('<option value="">No logins found...</option>');
}

function get_logins(data) {
	debug('done');

	if (data) {
		var strings = data.split("\n");
		var iHTML = '';
		for (var i = 0; i < strings.length ; i++ ) {
			if (strings[i]) {
				iHTML += '<option>' + strings[i] + '</option>';
			}
		}

		if (iHTML) {
			debug(iHTML);
			$('#logins').html(iHTML);
			$('#logins')[0].selectedIndex = -1;
		}
	}
}

function fill_login() {
	debug('get login');
	if ($('#logins').val()) {
		$.get( home + "?type=passcard&passcard=" + $('#logins').val(), {}, fill_form);		
		$('#logins')[0].selectedIndex = -1;
	}
}

function fill_form(data) {
	debug('done');
	port.postMessage({command: 'fillform', message: data});
}

function init() {
	$('#logins').bind("change", '', fill_login);
	debug('init');
}

function save_form() {
	debug('save');	
	port.postMessage({command: 'saveform'});
}

function showmessage(msg) {
	port.postMessage({command: 'alert', msg: msg});
}

function post_form(data) {
	$.get( home + "?type=save&passcard="+data.fn+"&url="+escape(data.url)+"&data=" + escape(data.data), {}, post_form_done);
}

function post_form_done() {
	showmessage('New login was successfully saved!');
}